<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <el-row style="margin-bottom: 10px">
        <el-button
          type="danger"
          @click="deleteImage(0)"
          icon="el-icon-remove-outline"
          class="btn"
        >
          批量删除
        </el-button>
        <el-button
          type="primary"
          @click="addImageDialog"
          icon="el-icon-circle-plus-outline"
          class="btn"
        >
          添加图片
        </el-button>
      </el-row>
      <div>
        <el-table
          :data="list"
          border
          style="width: 100%"
          @selection-change="handleSelectChange"
          v-loading="imageLoading"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            width="50"
            label="编号"
            align="center"
          />
          <el-table-column label="图片展示" align="center">
            <template slot-scope="scope">
              <el-image
                style="width: 150px; height: auto"
                :src="scope.row.imageUrl"
                fit="contain"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="imageUrl" label="图片路径" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-tooltip content="编辑图片" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editImageDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="删除图片" placement="top">
                <el-button
                  el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteIamge(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <edit-dialog
        :index="index"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :imageInfo="imageInfo"
        @cancel="cancel"
        @ok="ok"
      />
    </el-card>
  </div>
</template>

<script>
import {
  listImage,
  addImage,
  updateImage,
  deleteImageCarousel,
} from "@/api/home";
import editDialog from "./components/editDialog";

export default {
  name: "ImageCarousel",
  components: { editDialog },
  data() {
    return {
      list: [],
      multipleSelection: [], //复选框选中的所有数据
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      imageInfo: {},
      imageLoading: false,
      editDialogVisible: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑
    };
  },
  created() {
    this.imageLoading = true;
    this.getData();
  },
  methods: {
    getData() {
      const form = {
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      listImage(form)
        .then((res) => {
          if (res.data) {
            this.list = res.data.imageCarousels;
            // 返还每页显示的条数
            //this.paging.size = res.data.size;
            this.paging.total = res.data.totalCount;
            this.imageLoading = false;
          }
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.imageLoading = false;
        });
    },
    addImageDialog() {
      this.dialogTitle = "添加轮播图";
      this.editDialogVisible = true;
      this.index = 0;
    },
    editImageDialog(row) {
      this.dialogTitle = "修改轮播图";
      this.editDialogVisible = true;
      this.imageInfo = this.extendCopy(row);
      this.index = 1;
    },
    deleteImage(val) {
      let imageCarousels = [];
      if (val === 0) {
        imageCarousels = this.multipleSelection;
        if (imageCarousels.length === 0) return;
      } else {
        imageCarousels.push(val);
      }
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const data = {
            imageCarousels: imageCarousels,
            accountId: this.$store.getters.accountId,
          };
          const result = await deleteImageCarousel(data);
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) {
        c[i] = p[i];
      }
      return c;
    },
    // 获取到选中的所有数据
    handleSelectChange(val) {
      this.multipleSelection = [];
      val.forEach((value) => {
        this.multipleSelection.push(value);
      });
      console.log(this.multipleSelection);
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    cancel() {
      this.editDialogVisible = false;
      this.index = 1;
    },
    async ok(val) {
      const response = await this.editImageInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    editImageInfo(data) {
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // index !== 0
          const result = await updateImage(data);
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addImage(data);
          if (result.code === 200) {
            this.$message.success("添加成功");
            resolve(result);
          } else {
            this.$message.error("添加失败，请重试");
            reject(result);
          }
        }
      });
    },
  },
};
</script>

<style scoped>

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
</style>